#include <stdio.h>
#include "dominion.h"
#include "dominion_helpers.h"
#include <time.h>
#include <stdlib.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include "showGameState.h"
#include "globals.h"
#include <stdbool.h>
#include <assert.h>

void shuffleDiscards(int player, struct gameState *state)
{
    // Returns all cards in players discard pile to deck and shuffles deck
    int deckindex = state->deckCount[player];
    for (int i = 0; i < state->discardCount[player]; i++)
    {
        state->deck[player][deckindex + i] = state->discard[player][i];
        state->discard[player][i] = 0;
        state->deckCount[player]++;
    }
    state->discardCount[player] = 0;
    gsl_ran_shuffle(rng, state->deck[player], state->deckCount[player], sizeof(enum CARD));
}

void discardTopCard(int player, struct gameState *state)
{
    // Discards the top card from players deck
    state->discard[player][state->discardCount[player]] = state->deck[player][state->deckCount[player] - 1];
    state->deckCount[player]--;
    state->discardCount[player]++;
}

bool isTreasureCard(enum CARD c)
{
    return (c == copper || c == silver || c == gold);
}

void myAdventurerCard(int handpos, struct gameState *state)
{
    // Reveal cards from deck until 2 Treasure cards revealed
    // Put those 2 cards in hand, discard other revealed cards

    int player = state->whoseTurn;
    // enum CARD revealed_cards[MAX_HAND];
    int tc_count = 0;
    int i = 0;
    enum CARD currentCard;
    while  (tc_count < 2 && i < state->handCount[player && state->deckCount[player] > 0])
    {
// ******************************** deckCount is going negative!
        currentCard = state->deck[player][state->deckCount[player] - 1];
        state->deckCount[player]--;
        if (isTreasureCard(currentCard))
        {
            tc_count++;
            state->hand[player][state->handCount[player]] = currentCard;
            state->handCount[player]++;
        }
        else
        {
            // ************************************** this assertion fails sometimes!!!!
            assert (state->discardCount[player] < 500);
            state->discard[player][state->discardCount[player]] = currentCard;
            state->discardCount[player]++;        }
            i++;
    }

}

